<?PHP
#
#   FILE:  iCal.php (CalendarEvents plugin)
#
#   Part of the Metavus digital collections platform
#   Copyright 2013-2020 Edward Almasy and Internet Scout Research Group
#   http://metavus.net
#

use Metavus\Plugins\CalendarEvents\Event;
use Metavus\User;
use ScoutLib\iCalendar;
use ScoutLib\StdLib;

# ----- MAIN -----------------------------------------------------------------

# assume that a generic error will occur
$H_State = "Error";

# get object parameters
$EventId = StdLib::getArrayValue($_GET, "EventId");

# if the event ID looks invalid
if (!is_numeric($EventId)) {
    $H_State = "Invalid ID";
    return;
}

# if the event ID actually is invalid
if (!Event::ItemExists($EventId)) {
    $H_State = "Invalid ID";
    return;
}

$Event = new Event($EventId);

$H_Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

# if the entry is some other type of resource
if (!$H_Plugin->IsEvent($Event)) {
    $H_State = "Not Event";
    return;
}

# if the user can't view the event
if (!$Event->UserCanView(User::getCurrentUser())) {
    $H_State = "Viewing not permitted";
    return;
}

# everything is fine
$H_State = "OK";

# get start and end date to make sure we don't pass anything bad into iCalendar's constructor
$StartDate = $Event->Get("Start Date");
$EndDate = is_null($Event->Get("End Date")) ? $StartDate : $Event->Get("End Date");

if (is_null($StartDate) && is_null($EndDate)) {
    $H_State = "Invalid Date";
    return;
} elseif (is_null($StartDate)) {
    $StartDate = $EndDate;
}

# record an iCalendar file download
$H_Plugin->RecordEventiCalDownload($Event);

# construct the iCalendar document
$iCalendar = new iCalendar(
    $Event->Id(),
    $StartDate,
    $EndDate,
    $Event->Get("All Day")
);

# add the fields for the event
$iCalendar->AddCreated($Event->Get("Date Of Record Creation"));
$iCalendar->AddSummary(iCalendar::TransformHTMLToPlainText($Event->Get("Title")));
$iCalendar->AddDescription(iCalendar::TransformHTMLToPlainText(
    $Event->Get("Description")
));
$iCalendar->AddURL($Event->GetBestUrl());
$iCalendar->AddLocation($Event->OneLineLocation());
$iCalendar->AddCategories($Event->CategoriesForDisplay());

# set up the headers for printing the iCalendar document
$GLOBALS["AF"]->SuppressHTMLOutput();
header("Content-Type: text/Calendar; charset=".$AF->HtmlCharset(), true);
header("Content-Disposition: inline; filename=\"".$iCalendar->GenerateFileName()."\"");

# output the iCalendar document
print $iCalendar->GenerateDocument();
